# Copyright (c) 2021 Presto Labs Pte. Ltd.
# Author: leon

import requests
from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo
import re


def generate():
  mea = 'Futures.Phemex.v1'
  me = 'Futures.Phemex'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()
  data = requests.get("https://api.phemex.com/public/products").json()['data']['products']

  # special handle eth and btc symbol
  symbol_map = {
    "BTCUSD": {
      "symbol": "USD-BTC.PERPETUAL",
      "base": "BTC",
      "quote": "USD",
      "native_base": "BTC",
      "native_quote": "USD",
    },
    "uBTCUSD": {
      "symbol": "BTC-USD.PERPETUAL",
      "base": "BTC",
      "quote": "USD",
      "native_base": "BTC",
      "native_quote": "USD",
    },
    "cETHUSD": {
      "symbol": "USD-ETH.PERPETUAL",
      "base": "ETH",
      "quote": "USD",
      "native_base": "ETH",
      "native_quote": "USD",
    },
  }

  pis = []
  for info in data:
    if info["status"] == "Delisted":
      continue

    if info['type'] != 'Perpetual':
      continue
    native_symbol = info['symbol']
    if info['symbol'] in symbol_map:
      native_quote = symbol_map[info['symbol']]['native_quote']
      native_base = symbol_map[info['symbol']]['native_base']
      base = symbol_map[info['symbol']]['base']
      quote = symbol_map[info['symbol']]['quote']
      symbol = symbol_map[info['symbol']]['symbol']
    else:
      native_quote = info['quoteCurrency']
      native_base = native_symbol[:-len(native_quote)]
      base = symbol_info.native_to_norm_currency(mea, native_base)
      quote = symbol_info.native_to_norm_currency(mea, native_quote)
      symbol = "%s-%s.PERPETUAL" % (base, quote)

    is_inverse = symbol == "USD-ETH.PERPETUAL" or symbol == "USD-BTC.PERPETUAL"

    pi = dict(
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        price_ticksize=float(info['tickSize']),
        qty_ticksize=float(1),
        contract_value=float(info['contractSize']),
        is_inverse=is_inverse,
    )

    regex = "^U[0-9]{3,}"
    result = re.search(regex, base)
    if result:
      asset_multiplier = float(result.group(0)[1:])
      if result.start() == 0:
        asset = base[len(result.group(0)):]
      else:
        asset = base[:result.start()]
      pi["asset_multiplier"] = asset_multiplier
      pi["asset"] = asset

    pi = {**pi, **default.product_info(me, symbol)}
    pis.append(pi)

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


def gen_coin1_constants():
  data = generate()
  data = convert_coin1_constants(data)
  return data


def convert_coin1_constants(data):
  symbol_list = [info['native_symbol'] for info in data]
  quote_currency_list = [info['native_quote'] for info in data]
  base_currency_list = [info['native_base'] for info in data]
  currency_list = base_currency_list + quote_currency_list
  res = {
      'symbol_list': list(set(symbol_list)),
      'base_currency_list': list(set(base_currency_list)),
      'quote_currency_list': list(set(quote_currency_list)),
      'currency_list': list(set(currency_list)),
  }
  return res


if __name__ == "__main__":
  import json
  print(json.dumps(generate(), indent=2))
